import pjsua2 as pj
import logging
import xml.etree.ElementTree as ET
from .command_processor import CommandProcessor

class SipAccount(pj.Account):
    def __init__(self, handler, config):
        super().__init__()
        self.handler = handler
        self.config = config
        self.logger = logging.getLogger('SIP.Account')

    def onRegState(self, prm):
        if prm.code == 200:
            self.logger.info(f"注册成功, expires: {prm.expiration}秒")
        else:
            self.logger.error(f"注册失败: {prm.reason}")
    
    def onIncomingCall(self, prm):
        self.logger.warning("收到呼入请求，GB28181设备不应被呼入")
        call = pj.Call(self, prm.callId)
        call.answer(486, "Busy Here")

class SipHandler:
    def __init__(self, config, command_processor):
        self.config = config['sip']
        self.command_processor = command_processor
        self.logger = logging.getLogger('SIP')
        self.ep = pj.Endpoint()
        
        # 创建Endpoint
        ep_cfg = pj.EpConfig()
        self.ep.libCreate()
        self.ep.libInit(ep_cfg)
        
        # 创建UDP传输
        tcfg = pj.TransportConfig()
        tcfg.port = self.config['local_port']
        self.transport = self.ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, tcfg)
        
        # 启动库
        self.ep.libStart()
        self.account = None
        self.logger.info("SIP栈初始化完成")

    def register(self):
        """注册到SIP服务器"""
        acfg = pj.AccountConfig()
        acfg.idUri = f"sip:{self.config['device_id']}@{self.config['domain']}"
        acfg.regConfig.registrarUri = f"sip:{self.config['server_ip']}:{self.config['server_port']}"
        acfg.sipConfig.authCreds = [
            pj.AuthCredInfo(
                "digest", 
                self.config['domain'], 
                self.config['device_id'], 
                0, 
                self.config['password']
            )
        ]
        
        self.account = SipAccount(self, self.config)
        self.account.create(acfg)
        self.logger.info("开始注册到SIP服务器...")

    def unregister(self):
        """注销"""
        if self.account:
            self.account.setRegistration(False)
            self.logger.info("已发送注销请求")

    def send_message(self, content, content_type="Application/MANSCDP+xml"):
        """发送SIP MESSAGE"""
        if not self.account:
            self.logger.error("账户未注册，无法发送消息")
            return
        
        # 创建消息
        msg = pj.SendInstantMessageParam()
        msg.content = content
        msg.contentType = content_type
        
        # 目标URI
        to_uri = f"sip:{self.config['server_ip']}:{self.config['server_port']}"
        
        try:
            self.account.sendInstantMessage(pj.SendInstantMessageParam(to_uri, msg))
            self.logger.debug(f"已发送消息: {content[:100]}...")
        except pj.Error as e:
            self.logger.error(f"发送消息失败: {e.info()}")

    def on_rx_message(self, sender, content):
        """处理收到的SIP MESSAGE"""
        self.logger.debug(f"收到消息: {content[:200]}...")
        
        try:
            # 解析XML内容
            root = ET.fromstring(content)
            cmd_type = root.find('CmdType').text
            self.logger.info(f"收到命令: {cmd_type}")
            
            # 分派到命令处理器
            self.command_processor.process_command(root)
            
        except ET.ParseError:
            self.logger.error("XML解析失败")
        except AttributeError:
            self.logger.error("无效的XML结构")

    def send_invite(self, channel_id, sdp):
        """发送INVITE请求"""
        # 实现INVITE信令构造
        pass

    def send_bye(self, call_id):
        """发送BYE请求"""
        pass